package day18.解析xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class XmlParse {
    public static void main(String[] args) throws DocumentException {
        //获得一个解析器
        SAXReader saxReader = new SAXReader();
        //创建一个用来装学生对象的集合
        ArrayList<Student> list = new ArrayList<>();

        //用解析器把xml文件加载到内存当中
        Document document = saxReader.read(new File("study\\src\\Xml\\allPut.xml"));
        //获取根标签
        Element rootElement = document.getRootElement();
        //获取student标签
        List<Element> studentElements = rootElement.elements("student");
        for (Element element : studentElements) {
            //获取id这个属性
            Attribute attribute = element.attribute("id");
            String id = attribute.getValue();
            //获取name标签
            Element nameElement = element.element("name");
            //获取标签体内容
            String name = nameElement.getText();
            //获取age标签
            Element ageElement = element.element("age");
            String age = ageElement.getText();
            //System.out.println(id);
            //System.out.println(name);
            //System.out.println(age);
            Student s = new Student(id, name, Integer.parseInt(age));
            list.add(s);
        }
        for (Student student : list) {
            System.out.println(student);
        }
    }
}
